package cn.com.xxlibrary.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.google.code.kaptcha.Producer;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Namespace(value = "/")
//@ExceptionMappings({ @ExceptionMapping(exception = "java.lang.Exception", result = "error") })
public class Captcha extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private Producer captchaProducer = null;

	private ByteArrayInputStream capImage;


	@Action(value = "Captcha", results = { @Result(name = SUCCESS, type = "stream", params = {
			"contentType", "image/jpeg", "inputName", "capImage", "bufferSize",
			"2048" }) })
	public String captcha() throws IOException {
		// 获取验证码字符串
		String capText = captchaProducer.createText();
		ActionContext.getContext().getSession()
				.put("SESSION_SECURITY_CODE", capText);
		BufferedImage bi = captchaProducer.createImage(capText);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);  
		ImageIO.write(bi, "jpg", imageOut);
		imageOut.close();
		capImage = new ByteArrayInputStream(output.toByteArray());
		return SUCCESS;
	}

	public Producer getCaptchaProducer() {
		return captchaProducer;
	}

	public void setCaptchaProducer(Producer captchaProducer) {
		this.captchaProducer = captchaProducer;
	}

	public ByteArrayInputStream  getCapImage() {
		return capImage;
	}

	public void setCapImage(ByteArrayInputStream capImage) {
		this.capImage = capImage;
	}

}
